import { createRouter, createWebHashHistory } from "vue-router";
import nprogress from "nprogress";
import Pinia from "@/store";
import "nprogress/nprogress.css";
import useAuthStore from "@/store/modules/auth";
import setting from "@/setting";

nprogress.configure({ showSpinner: false }); // 配置nprogress
// 检查token是否存在
const authStore = useAuthStore(Pinia);

const router = createRouter({
  history: createWebHashHistory(),
  routes: authStore.menuRoutes,
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});

// 路由前置守卫
router.beforeEach((to: any, _, next: any) => {
  nprogress.start(); // 开始加载进度条

  if (
    //导航到目的路径meta包含requiresAuth
    to.path != "/login" &&
    to.matched.some((record: any) => record.meta?.requiresAuth)
  ) {
    // console.log(authStore.tokenObj);
    //不含token
    if (!authStore.tokenObj.access_token) {
      next({ path: "/login", query: { redirect: to.fullPath } });
    } else {
      next(); // 包含token
    }
  } else {
    next();
  }
});

// 路由后置守卫
router.afterEach((to: any, _) => {
  nprogress.done(); // 结束加载进度条
  document.title = `${setting.title} - ${to.meta.title}`;
});

export default router;
